//
//  NativeSelfRenderAdView.m
//  JAGatherAdDemo
//
//  Created by Yc on 2024/2/19.
//

#import "NativeSelfRenderAdView.h"
#import <Masonry.h>
#import "Header.h"

@interface NativeSelfRenderAdView ()

@property (nonatomic, strong) NSMutableArray *clickViews;

@property (nonatomic, strong) UIStackView *stackView;

@end

@implementation NativeSelfRenderAdView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (instancetype)init {
    NSAssert(NO, @"Please use initWithFrame: to initialize");
    return nil;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    NSAssert(NO, @"Please use initWithFrame: to initialize");
    return nil;
}

- (void)setupUI {
    if (!_adMeta) return;
    
    [self.clickViews removeAllObjects];
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    JAGCreativeType type = [_adMeta metaCreativeType];
    
    CGSize logoSize = CGSizeMake(0, 0);
    if ([_adMeta metaLogoView]) {
        self.logoView = [_adMeta metaLogoView];
        if (self.logoView.image) {
            CGFloat logoH = 15;
            CGFloat logoW = logoH / self.logoView.image.size.height * self.logoView.image.size.width;
            logoSize = CGSizeMake(ceil(logoW), logoH);
        }
    }
    
    [self addSubview:self.imageView];
    [self addSubview:self.titleLabel];
    [self addSubview:self.logoView];
    [self addSubview:self.contentLabel];
    [self addSubview:self.dislikeButton];
    
    ViewRadius(self.imageView, 5);
    
    if (type == JAGCreativeTypeMultiImage) {
        // 多图
        [self addSubview:self.stackView];
        [self.stackView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.leading.equalTo(self).offset(10);
            make.trailing.equalTo(self).offset(-10);
            make.height.equalTo(@80);
        }];
        
        NSArray *imageUrls = [_adMeta metaImageUrls];
        for (NSInteger i = 0; i < imageUrls.count; i++) {
            UIImageView *imageView = [UIImageView new];
            imageView.layer.masksToBounds = YES;
            imageView.layer.cornerRadius = 2;
            [self.stackView addArrangedSubview:imageView];
        }
        
        [self.logoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self).offset(10);
            make.bottom.equalTo(self.mas_bottom).offset(-8);
            make.size.mas_equalTo(logoSize);
        }];
        
        [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.logoView.mas_trailing).offset(5);
            make.centerY.equalTo(self.logoView);
            make.trailing.equalTo(self).offset(-50);
        }];
        
        [self.dislikeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self).offset(-10);
            make.centerY.equalTo(self.contentLabel);
            make.size.mas_equalTo(CGSizeMake(25, 25));
        }];
        
        self.mediaView.hidden = YES;
        self.imageView.hidden = YES;
        self.titleLabel.hidden = YES;
        
        [self.clickViews addObjectsFromArray:@[self.contentLabel,self.logoView]];
        [self.clickViews addObjectsFromArray:self.stackView.arrangedSubviews];
        
    } else {
        
        // 单图 || 视频
        [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.top.equalTo(self).offset(15);
            make.size.mas_equalTo(CGSizeMake(140, 90));
        }];
        
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.imageView.mas_trailing).offset(10);
            make.trailing.equalTo(self).offset(-10);
            make.top.equalTo(self.imageView);
        }];
        
        [self.logoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.imageView.mas_trailing).offset(10);
            make.bottom.equalTo(self.imageView.mas_bottom);
            make.size.mas_equalTo(logoSize);
        }];
        
        [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.logoView.mas_trailing).offset(5);
            make.leading.mas_greaterThanOrEqualTo(self.imageView.mas_trailing).offset(10);
            make.bottom.equalTo(self.imageView.mas_bottom);
            make.trailing.equalTo(self).offset(-50);
        }];
        
        [self.dislikeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self).offset(-10);
            make.centerY.equalTo(self.contentLabel);
            make.size.mas_equalTo(CGSizeMake(25, 25));
        }];
        
        // 视频类型广告 获取播放器
        if (type == JAGCreativeTypeVideo) {
            
            JAGFeedVideoConfig *config = [[JAGFeedVideoConfig alloc] init];
            config.mediaFrame = CGRectMake(15, 15, 140, 90);
            config.isMute = YES;
            UIView *mediaView = [_adMeta getMediaView:config];
            if (mediaView) {
                self.mediaView = mediaView;
                [self addSubview:self.mediaView];
                ViewRadius(self.mediaView, 5);
                [self.mediaView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.leading.top.equalTo(self).offset(15);
                    make.size.mas_equalTo(CGSizeMake(140, 90));
                }];
                
                [self.clickViews addObject:self.mediaView];
            }
        }
        
        self.mediaView.hidden = type == JAGCreativeTypeVideo ? NO : YES;
        self.imageView.hidden = type == JAGCreativeTypeVideo ? YES : NO;
        
        [self.clickViews addObjectsFromArray:@[self.titleLabel,self.contentLabel,self.imageView,self.logoView]];
    
    }
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    // 更新logo size
    if (self.logoView.image && !CGSizeEqualToSize(self.logoView.image.size, CGSizeMake(0, 0)) && self.logoView.superview) {
        CGFloat logoH = 15;
        CGFloat logoW = logoH / self.logoView.image.size.height * self.logoView.image.size.width;
        CGSize logoSize = CGSizeMake(ceil(logoW), logoH);
        [self.logoView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(logoSize);
        }];
    }
}

- (void)setAdMeta:(id<JAGFeedAdMeta>)adMeta {
    _adMeta = adMeta;
    [self setupUI];
    [self updateData];
}

- (void)updateData {
    if (!_adMeta) return;
    JAGCreativeType type = [_adMeta metaCreativeType];
    NSString *title = [_adMeta metaTitle];
    NSString *content = [_adMeta metaContent];

    if (title.length>0) {
        self.titleLabel.text = title;
    }
    if (content.length>0) {
        self.contentLabel.text = content;
    }
    [self showImage:self.imageView url:[_adMeta metaImageUrl] completion:nil];
    if (![_adMeta metaLogoView]) {
        // 物料中平台logo metaLogoView为空的则请求metaLogoUrl 展示广告logo
        __weak typeof(self) ws = self;
        [self showImage:self.logoView url:[_adMeta metaLogoUrl] completion:^{
            __strong typeof(ws) self = ws;
            [self setNeedsLayout];
            [self layoutIfNeeded];
        }];
    }
    // 因各平台返回广告logo素材方式和尺寸有差异，若需自定义显示广告logo，可通过以下方式隐藏广告平台默认存在的logo视图
//    [_adMeta hiddenAdPlatformLogo];
    
    if (type == JAGCreativeTypeMultiImage) {
        // 多图
        NSArray *imageUrls = [_adMeta metaImageUrls];
        [self.stackView.arrangedSubviews enumerateObjectsUsingBlock:^(__kindof UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx < imageUrls.count) {
                [self showImage:obj url:imageUrls[idx] completion:nil];
            }
        }];
    }
    
    NSLog(@"自渲染素材：\n type: %zd\n title: %@\n content: %@\n icon: %@\n logoUrl: %@\n imgUrl: %@\n metaVideoUrl: %@\n imageUrls: %@\n",type,title,content,[_adMeta metaIconUrl],[_adMeta metaLogoUrl],[_adMeta metaImageUrl],[_adMeta metaVideoUrl],[_adMeta metaImageUrls]);
}

- (void)showImage:(UIImageView *)imageView url:(NSString *)url completion:(void (^)(void))completion {
    if (!imageView || url.length < 0) {
        return;
    }
    __block NSURL *iconURL = [NSURL URLWithString:url];
    __block UIImageView *view = imageView;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        NSData *iconData = [NSData dataWithContentsOfURL:iconURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:iconData];
            view.image = image;
            if (completion) {
                completion();
            }
        });
    });
}

#pragma mark - Action
- (void)clickDislikeButton:(UIButton *)sender {
    [self.adMeta destroyAd];
    if (self.tapDislikeBlock) {
        self.tapDislikeBlock();
    }
}

#pragma mark - Public

/// 绑定广告数据
- (void)registerDataObject {
    // 将广告与UIView进行绑定：广告容器 传入前需设置frame
    [self.adMeta attachAd:self
                clickView:self.clickViews];
}

/// 解绑广告数据 如果调用了registerDataObject:方法  一定要在适当的时机  调用unregisterDataObject方法
- (void)unregisterDataObject {
    [self.adMeta unAttachAd];
}

#pragma mark - Lazy
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:15];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.numberOfLines = 2;
        _titleLabel.text = @"广告";
    }
    return _titleLabel;
}

- (UILabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] init];
        _contentLabel.font = [UIFont systemFontOfSize:12];
        _contentLabel.textColor = [UIColor lightGrayColor];
        _contentLabel.text = @"广告";
    }
    return _contentLabel;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.userInteractionEnabled = YES;
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.backgroundColor = [UIColor lightGrayColor];
    }
    return _imageView;
}

- (UIImageView *)logoView {
    if (!_logoView) {
        _logoView = [[UIImageView alloc] init];
        _logoView.userInteractionEnabled = YES;
        _logoView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _logoView;
}

- (UIButton *)dislikeButton {
    if (!_dislikeButton) {
        _dislikeButton = [[UIButton alloc] init];
        _dislikeButton.titleLabel.font = [UIFont systemFontOfSize:18];
        [_dislikeButton setTitle:@"x" forState:UIControlStateNormal];
        [_dislikeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_dislikeButton addTarget:self action:@selector(clickDislikeButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dislikeButton;
}

- (NSMutableArray *)clickViews {
    if (!_clickViews) {
        _clickViews = [[NSMutableArray alloc] init];
    }
    return _clickViews;
}

- (UIStackView *)stackView {
    if (!_stackView) {
        _stackView = [[UIStackView alloc] init];
        _stackView.spacing = 5;
        _stackView.axis = UILayoutConstraintAxisHorizontal;
        _stackView.distribution = UIStackViewDistributionFillEqually;
        _stackView.alignment = UIStackViewAlignmentFill;
    }
    return _stackView;
}

@end
